import 'package:flutter/material.dart';
import 'package:flutter_app/providerlearn/counter_provider.dart';
import 'package:provider/provider.dart';

class MyPage extends StatefulWidget {
  const MyPage({Key? key}) : super(key: key);

  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  @override
  Widget build(BuildContext context) {
    var _counterProvider = CounterProvider();
    return ChangeNotifierProvider<CounterProvider>(
      create: (context) => _counterProvider,
      child: createScaffold(_counterProvider, 2),
    );
  }

  Widget createScaffold(CounterProvider counterProvider, int type) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('myPage'),
      ),
      body: type == 1
          ? createShowDataPage()
          : createShowDatasPage(counterProvider),
      floatingActionButton:
          type == 1 ? createFloatingActionButton(counterProvider) : null,
    );
  }

  Widget createShowDataPage() {
    return Center(
      child:
          Consumer<CounterProvider>(builder: (context, counterProvider, child) {
        debugPrint('text重绘');
        return Text(
          'value:${counterProvider.value}',
          style: const TextStyle(fontSize: 20),
        );
      }),
    );
  }

  createShowDatasPage(CounterProvider counterProvider) {
    return Center(
      child: Column(
        children: <Widget>[
          Selector<CounterProvider, int>(
            builder: (context, data, child) {
              return Text(
                '按钮1当前计数:${data.toString()}',
                style: const TextStyle(fontSize: 20),
              );
            },
            selector: (context, counterProvider) {
              return counterProvider.value;
            },
          ),
          Selector<CounterProvider, int>(
            builder: (context, data, child) {
              return Text(
                '按钮2当前计数:${data.toString()}',
                style: const TextStyle(fontSize: 20),
              );
            },
            selector: (context, counterProvider) {
              return counterProvider.value1;
            },
          ),
          ElevatedButton(
            onPressed: () {
              counterProvider.increment();
            },
            child: const Text('增加按钮1', style: TextStyle(fontSize: 20)),
          ),
          ElevatedButton(
            onPressed: () {
              counterProvider.increment1();
            },
            child: const Text('增加按钮2', style: TextStyle(fontSize: 20)),
          ),
        ],
      ),
    );
  }

  createFloatingActionButton(CounterProvider counterProvider) {
    return FloatingActionButton(
      child: const Icon(Icons.navigation),
      onPressed: () => counterProvider.increment(),
    );
  }
}
